package cn.yunyichina.provider.message.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.message.dao.ResendRuleDao;
import cn.yunyichina.provider.message.entity.ResendRule;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * 消息重发规则
 */
@Service("resendruleServiceImpl")
public class ResendRuleServiceImpl implements InitializingBean,Runnable {
	
	private static Logger logger = LoggerFactory.getLogger(MsgServiceImpl.class);
	
	@Autowired
	private ResendRuleDao resendRuleDao;
	
	
	/**
	 * 根据id获取重发规则<br>
	 * 先从缓存获取，如果缓存获取不到，则重新加载所有重发规则到缓存
	 * @param id 消息重发规则ID，或者是一个包含id的JSON字符串
	 * @return 如果找不到，返回null
	 */
	public ResendRule getResendRule(String id) {
		logger.debug("getResendRule入口：id="+id);
		if (StringUtils.isBlank(id)) {
			throw new CallException(ErrorCodeDefine.MESSAGE_VALUE, "重发规则ID不允许为空");
		}
		if (id.startsWith("{")) {
			JSONObject param = JsonUtils.parseObject(id);
			id = param.getString("id");
		}
		ResendRule rule = new ResendRule();
		rule.setId(id);
		
		List<ResendRule> listRule = resendRuleDao.select(rule);
		if (listRule.size() > 0) {
			return listRule.get(0);
		}
		
		return null;
	}

	/**
	 * 根据id获取重发规则<br>
	 * 先从缓存获取，如果缓存获取不到，则重新加载所有重发规则到缓存
	 * @param id 消息重发规则ID，或者是一个包含id的JSON字符串
	 * @return 如果找不到，返回null
	 */
	public ResendRule getResendRuleCache(String id) {
		logger.debug("getResendRule入口：id="+id);
		if (id.startsWith("{")) {
			JSONObject param = JsonUtils.parseObject(id);
			id = param.getString("id");
		}
		
		String strJson = CacheService.getGlobalKey("message", "resend", id);
		if (StringUtils.isBlank(strJson) || "nil".equals(strJson)) {
			
			loadToCache();
			
			strJson = CacheService.getGlobalKey("message", "resend", id);
		}
		
		if (StringUtils.isBlank(strJson) || "nil".equals(strJson)) {
			return null;
		}
		
		logger.debug("getResendRule结果：rule="+JsonUtils.toJsonString(strJson));
		
		return JsonUtils.parseObject(strJson, ResendRule.class);
	}
	
	/**
	 * 将全部数据加入到缓存
	 */
	public void loadToCache() {
		try {
			logger.debug("加载消息重发规则到缓存");
			List<ResendRule> listRule = resendRuleDao.select();
			logger.debug("规则数量:"+listRule.size());
			for (ResendRule rule : listRule) {
				CacheService.setGlobalKey("message", "msg_resend_rule", rule.getId(), JsonUtils.toJsonString(rule), 24*3600);
			}
			logger.debug("加载消息重发规则到缓存成功");
		}
		catch (Exception ex) {
			logger.error("加载消息重发规则到缓存失败");
			logger.error(ErrorCodeDefine.getStackTrace(ex));
		}
	}

	@Override
	public void run() {
		logger.info("消息重发规则加载线程启动。。。。。。。。。。。。。");
		while (true) {
			try {
				loadToCache();
			}
			catch (Exception ex) {
				logger.error("加载重发消息规则错误："+ErrorCodeDefine.getStackTrace(ex));
			}
			finally {
				try {
					Thread.currentThread().sleep(10*60*1000);//重新加载
				}
				catch (Exception ex2) {
					
				}
			}
		}
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
//		new Thread(this).start();
		
	}
	
	
	
}
